import axios from "axios";
import type { AxiosInstance, AxiosRequestConfig } from 'axios'
import { open,close } from "@/components/loader/loader";
import { message } from "antd";


interface axiosConfig extends AxiosRequestConfig {
    showLoading?: boolean
}


const baseURL:string = "http://10.2.220.142:5050"

export function axiosInstance(config?: axiosConfig): AxiosInstance {
  const instance = axios.create({
    baseURL:baseURL,
    timeout: 10000, // 超时配置
    withCredentials: false, // 跨域携带cookie
    ...config, // 自定义配置覆盖基本配置
  })

  const showLoading = config?.showLoading === undefined ? true : config?.showLoading

  // 添加请求拦截器
  instance.interceptors.request.use(
    (config: any) => {
      if (showLoading)
        open()
      return config
    },
    (error) => {
      return Promise.reject(error)
    },
  )

  // 添加响应拦截器
  instance.interceptors.response.use(
    (response:any) => {
      if (showLoading)
         close()
      const { code,data,message} = response.data
      //後端需具體返回message，將message全部提示系統異常！
      //將data解構，不需要臃腫的response
      if (code === 200 && data.length !== 0) { return [data,message] }
      //操作類的sql返回執行成功
      else if(code === 200 && data.length === 0){
        return message
      }
      else if(code === 0){
        return Promise.reject(message)
      }
      else {
        //獲取文件流時返回
        if(response.headers["content-type"] === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
          response.headers["content-type"] === "application/octet-stream"
        ){
          return Promise.resolve(response.data)
        }
        else
         return data
      }
    },
    (error) => {
      if (showLoading)
        close()
        message.error(error?.response?.data?.message || '请求错误')
      return Promise.reject(error)
    },
  )
  return instance
}
